import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
import { Form, message, Switch, Button, Modal, Upload, Select, Input, Radio, Icon } from 'antd'
import { widgetType } from 'constants'
import PropTypes from 'prop-types'
import Style from './creator.css'

const { confirm } = Modal
const { Option } = Select
const { TextArea } = Input
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}
class RecycleForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    addAuthor: PropTypes.func,
    author: PropTypes.any
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      editParams: {},
      searchParams: {
        pageNo: 1,
        pageSize: 20
      }
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
    this.handleEdit = this.handleEdit.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.onChange = this.onChange.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
  }

  getFilterCols () {
    return [
      {
        label: '输入搜索',
        id: 'searchField',
        widget: widgetType.input,
        placeholder: '请输入'
      },
      {
        label: false,
        span: 16,
        key: 'custom',
        widget: 'custom',
        formItemLayout: {},
        render: () => {
          return (
            <>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.search}>查询</Button>
              <Button style={{ marginRight: 10 }} onClick={this.reset}>重置</Button>
              <Button type='primary' onClick={this.handleAdd}>新建Mua</Button>
            </>
          )
        }
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: 'Mua编号',
        dataIndex: 'code',
        key: 'code',
        width: 100,
        sorter: (a, b) => a.id - b.id
      },
      {
        title: '创作者（Mua）',
        dataIndex: 'name',
        key: 'name',
        width: 100
      },
      {
        title: '是否禁用',
        dataIndex: 'enabledFlag',
        key: 'enabledFlag',
        width: 100,
        render: (text, row, index) => <Switch size='small' checked={(text === 0)} onChange={(value) => this.handleSwitchChange(value, row, index)} />
      },
      {
        title: '相关联',
        dataIndex: 's',
        key: 's',
        width: 100,
        render: (text, record) => <div className={Style['related-container']}>
          <div className={Style['related']}>商品：<span>{record.commodityCount}</span></div>
          <div>关注：<span>{record.likeCount}</span></div>
        </div>
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <>
            <a className={Style['a-btn']} onClick={() => this.handleEdit(record)}>编辑</a>
            {/* <Popconfirm placement='top' title='确认是否删除' onConfirm={() => this.handleDel(record.id)}>
              <a className={Style['a-btn']}>删除</a>
            </Popconfirm> */}
          </>
        },
        width: 100
      }
    ]
  }

  handleSwitchChange (value, row, index) {
    if (value) {
      confirm({
        title: '确认是否禁用',
        content: '作者取消显示后，他的作品会全部下架，请确认',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.switchChange(value, row.id)
        },
        onCancel: () => {
          this.refresh()
        }
      })
    } else {
      this.switchChange(value, row.id)
    }
  }

  beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG/PNG格式的图片!')
      this.setState({
        loading: false
      })
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 64
    if (!isLt2M) {
      message.error('图片大小 64MB!')
      this.setState({
        loading: false
      })
      return false
    }
    return isJpgOrPng && isLt2M
  }

  handleAdd () {
    this.setState({
      showModal: true,
      title: '新增Mua',
      formStatus: 'add',
      editParams: {},
      image: null
    })
  }

  handleEdit (params) {
    this.setState({
      showModal: true,
      title: '编辑Mua',
      formStatus: 'edit',
      editParams: params,
      image: params.avatar
    })
  }

  switchChange (value, id) {
    this.props.isShowCreater({
      id,
      enabledFlag: value ? 0 : 1
    })
  }

  handleOk () {
    const { image, formStatus, editParams } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.avatar = image
        if (formStatus === 'edit') {
          values.id = editParams.id
          this.props.editCreater(values)
        } else {
          this.props.addAuthor(values)
        }
        this.setState({
          showModal: false,
          image: null
        })
      }
    })
  }

  handleCancel () {
    this.setState({
      showModal: false,
      title: '',
      formStatus: null
    })
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      searchParams: {}
    })
    const { form } = this.props
    form.resetFields()
    this.props.getAuthor({
      pageNo: 1,
      pageSize: 20
    })
  }
  search () {
    const { pageSize, pageNo } = this.state
    let params = {
      pageSize, pageNo
    }

    // eslint-disable-next-line handle-callback-err
    this.props.form.validateFieldsAndScroll((err, values) => {
      params.searchField = values.searchField
      this.setState({
        searchParams: params
      })
      this.props.getAuthor(params)
    })
  }

  refresh () {
    const { searchParams } = this.state
    this.props.getAuthorRefresh(searchParams)
  }

  onPageChange (pageNo, pageSize) {
    const { searchParams } = this.state
    searchParams.pageNo = pageNo
    searchParams.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getAuthor(searchParams)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { searchParams } = this.state
    searchParams.pageNo = current
    searchParams.pageSize = pageSize
    this.props.getAuthor(searchParams)
  }

  handleDel (id) {
    this.props.delCreater({
      id
    })
  }

  onChange ({ file, fileList, event }) {
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      this.setState({
        loading: false
      })
      message.error('上传失败')
    }

    if (file.status === 'done') {
      this.setState({
        loading: false,
        image: file.response && file.response.data.imageUrl
      })
    }

    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  componentDidMount () {
    const { pageSize, pageNo } = this.state
    this.props.getAuthor({
      pageSize, pageNo
    })
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.addAuthorRequest && nextProps.addAuthorRequest) {
      message.success('添加成功')
      this.search()
    }

    if (!this.props.delCreaterRequest && nextProps.delCreaterRequest) {
      message.success('删除成功')
      this.search()
    }

    if (!this.props.editCreaterRequest && nextProps.editCreaterRequest) {
      message.success('编辑成功')
      this.search()
    }

    if (!this.props.isShowRequest && nextProps.isShowRequest) {
      message.success('操作成功')
      this.refresh()
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { pageNo, pageSize, showModal, loading, image, title, editParams } = this.state
    const { form, author } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: author && author.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }

    const uploadButton = (
      <div className={Style[`${image ? '' : 'image-container'}`]}>
        {
          image ? <div className={Style['image']} style={{ backgroundImage: `url(${image})` }} /> : <>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className={Style['ant-upload-text']}>Upload</div></>
        }
      </div>
    )
    return (

      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Filters cols={this.getFilterCols()} form={form} actions={false} search={this.search} reset={this.reset}>
              {/* <Button type='primary' onClick={this.handleAdd}>新建Mua</Button> */}
            </Filters>
            <CustomTable loading={!author} columns={this.getTableCols()} dataSource={(author && author.list) || []} pagination={pagination} />
            <Modal
              title={title}
              visible={showModal}
              width={600}
              onOk={this.handleOk}
              destroyOnClose
              onCancel={this.handleCancel}
            >
              <Form {...formItemLayout}>
                <Form.Item label='创作者姓名'>
                  {getFieldDecorator('name', { rules: [{ required: true, message: '请输入创作者' }], initialValue: editParams.name })(
                    <Input placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='年龄'>
                  {getFieldDecorator('age', { initialValue: editParams.age })(
                    <Input placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='性别'>
                  {getFieldDecorator('gender', { initialValue: editParams.gender })(
                    <Select placeholder='请选择性别'>
                      <Option value='1'>男</Option>
                      <Option value='2'>女</Option>
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label='创作者LOGO' extra={<span style={{ fontSize: '14px', color: 'rgba(0, 0, 0, 0.35)' }}>只能上传jpg/png格式，图片大小限定1～3M</span>}>
                  {getFieldDecorator('avatar', {
                    valuePropName: 'picture',
                    initialValue: image,
                    rules: [{ required: true, message: '请选上传创作者LOGO' }]
                  })(
                    <Upload
                      action='/file/upload/1.0'
                      name='file'
                      onChange={this.onChange}
                      showUploadList={false}
                      withCredentials
                      beforeUpload={this.beforeUpload}
                      headers={{
                        token: localStorage.getItem('token') || ''
                      }}
                    >
                      {uploadButton}
                      <Button type='primary'>
                        <Icon type='cloud-upload' /> 选择上传图片
                      </Button>
                    </Upload>
                  )}

                </Form.Item>
                <Form.Item label='创作者评论'>
                  {getFieldDecorator('profile', {
                    rules: [{ required: true, message: '请输入创作者评论' }],
                    initialValue: editParams.profile
                  })(
                    <TextArea placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='创作者身份'>
                  {getFieldDecorator('dignity', { rules: [{ required: true, message: '请输入创作者身份' }], initialValue: editParams.dignity })(
                    <Input placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='是否禁用' help='当创作者下还没有商品的时候，将不会显示该创作者'>
                  {getFieldDecorator('enabledFlag', {
                    valuePropName: 'radio',
                    initialValue: editParams.enabledFlag || 0
                  })(
                    <Radio.Group defaultValue={0}>
                      <Radio value={0}>是</Radio>
                      <Radio value={1}>否</Radio>
                    </Radio.Group>)}
                </Form.Item>
                <Form.Item label='创作者标签'>
                  {getFieldDecorator('tags', { initialValue: editParams.tags })(
                    <TextArea placeholder='请输入' />
                  )}
                </Form.Item>
              </Form>
            </Modal>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  addAuthorRequest: state.goods.addAuthorRequest,
  author: state.goods.author,
  delCreaterRequest: state.goods.delCreaterRequest,
  editCreaterRequest: state.goods.editCreaterRequest,
  isShowRequest: state.goods.isShowRequest
})
const mapDispatch = dispatch => ({
  addAuthor: dispatch.goods.addAuthor,
  getAuthor: dispatch.goods.getAuthor,
  delCreater: dispatch.goods.delCreater,
  isShowCreater: dispatch.goods.isShowCreater,
  editCreater: dispatch.goods.editCreater,
  getAuthorRefresh: dispatch.goods.getAuthorRefresh
})

const Recycle = Form.create()(RecycleForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Recycle)
)
